package cn.bluedot.controller;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bluedot.bean.Message;
import cn.bluedot.dao.UserMapper;
import cn.bluedot.model.User;
import cn.bluedot.model.UserExample;
import cn.bluedot.util.VerifyCode;
@Controller
public class UserController {
    @Autowired
    private UserMapper userDao;
    
    @RequestMapping(value="/loginSubmit", method=RequestMethod.POST)
    @ResponseBody
    public Object login(@Valid User loginUser,  
            Errors errors, HttpSession session) {
        Message msg = null;
        if (errors.hasErrors()) {
            msg = new Message(1, errors.getFieldErrors().get(0).getDefaultMessage());
        } else {
            msg = new Message(1, "");
            UserExample example = new UserExample();
            example.createCriteria().andAccountEqualTo(loginUser.getAccount());
            List<User> uList = userDao.selectByExample(example);
            User user = uList.isEmpty()? null : uList.get(0);
            if (user != null) {
                if (user.getPassword().equals(loginUser.getPassword())) {
                    // login success
                    user.setPassword(null);
                    session.setAttribute("user", user);
                    msg.setState(0);
                    return msg;
                } else {
                    msg.setMsg("密码不正确");
                }
            } else {
                msg.setMsg("账号不存在");
            }
            msg.setData(loginUser);
        }
        return msg;
    }
    
    @RequestMapping("/imageVailCode.do")
    @ResponseBody
    public Message verifyImage() {
        /**
         * 生成一个base64编码的图片序列
         */
        Message msg = new Message();
        VerifyCode verifyCode = new VerifyCode();
        BufferedImage image = verifyCode.getImage();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            VerifyCode.output(image, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String i_str = Base64.getEncoder().encodeToString(os.toByteArray());
        CFImage cfi = new CFImage();
        cfi.text = verifyCode.getText().toUpperCase();
        cfi.image = i_str;
        msg.setData(cfi);
        return msg;
    }
    
    static class CFImage {
        public String image;
        public String text;
    }
}
